package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.base.utils.StringUtils;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.oa.core.entity.com.ContractPerform;
import com.fz.us.oa.core.entity.com.PerformDetail;
import com.fz.us.oa.core.service.com.ContractDealService;
import com.fz.us.oa.core.service.com.ContractPerformService;
import com.fz.us.oa.core.service.com.CustomerInfoService;
import com.fz.us.oa.core.service.com.PerformDetailService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by dzw on 2017/12/4.
 */
@Controller
@RequestMapping(value = "/com/contractPerform")
public class ContractPerformController extends BaseController {
    private static final long serialVersionUID = -1143223360752350742L;

    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private CustomerInfoService customerInfoService;
    @Autowired
    private ContractDealService contractDealService;
    @Autowired
    private ContractPerformService contractPerformService;
    @Autowired
    private PerformDetailService performDetailService;

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = null;

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", new BaseEnumManager.StateEnum[]{BaseEnumManager.StateEnum.Enable, BaseEnumManager.StateEnum.Delete});

        searchResult = contractPerformService.paging(null,null,order,
                "com.fz.us.oa.core.entity.com.ContractPerform",
                new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);

        List<ContractPerform> contractPerformList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(ContractPerform contractPerform: contractPerformList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",contractPerform.getId());
            rMap.put("custName",contractPerform.getCustomerInfo()==null?"":contractPerform.getCustomerInfo().getName());
            rMap.put("contractName",contractPerform.getContractDeal()==null?"":contractPerform.getContractDeal().getName());
            BigDecimal billing = performDetailService.getPerformNum(contractPerform,"billing");
            BigDecimal receipts = performDetailService.getPerformNum(contractPerform,"receipts");
            rMap.put("billing",billing);
            rMap.put("receipts",receipts);
            rMap.put("result",billing.subtract(receipts));
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            ContractPerform contractPerform=contractPerformService.get(keyId);
            model.addAttribute("keyId", keyId);
            model.addAttribute("contractPerform", contractPerform);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/contractPerform_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            ContractPerform contractPerform=contractPerformService.get(keyId);
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);

            model.addAttribute("stepNo", stepNo);
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("contractPerform", contractPerform);

            BigDecimal billing = performDetailService.getPerformNum(contractPerform,"billing");
            BigDecimal receipts = performDetailService.getPerformNum(contractPerform,"receipts");
            model.addAttribute("billing", billing);
            model.addAttribute("receipts", receipts);
            model.addAttribute("result", billing.subtract(receipts));
        }

        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/contractPerform_read";
    }

    /**
     * 选择合同成交
     */
    @RequestMapping(value = "chooseDeal", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String chooseDeal() {
        return "/com/contractDeal_dialog";
    }

    public ContractPerform setData(User user, String keyId, String contractDealId, String customerInfoId, String signDate, BigDecimal contractMoney){
        ContractPerform contractPerform=null;
        if(StringUtils.isEmpty(keyId)){
            contractPerform=new ContractPerform();
            contractPerform.setCompany(user.getCompany());
        }else{
            contractPerform=contractPerformService.get(keyId);
        }
        contractPerform.setContractDeal(contractDealService.get(contractDealId));
        contractPerform.setCustomerInfo(customerInfoService.get(customerInfoId));
        contractPerform.setSignDate(DataUtil.StringToDate(signDate));
        contractPerform.setContractMoney(contractMoney);

        return contractPerform;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user, String keyId, String contractDealId, String customerInfoId, String signDate, BigDecimal contractMoney) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractPerform contractPerform=setData(user,keyId,contractDealId,customerInfoId,signDate,contractMoney);
        if(StringUtils.isNotEmpty(keyId)){
            contractPerformService.update(contractPerform);
            rMap.put("message", "更新成功");
        } else {
            contractPerformService.save(contractPerform, "com.fz.us.oa.core.entity.com.ContractPerform");
            rMap.put("message","保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交
     */
    @RequestMapping(value = "commit", method = RequestMethod.POST)
    public Object commit(@CurrentUser User user, String keyId, String contractDealId, String customerInfoId, String signDate, BigDecimal contractMoney, String curDutyId, String comment) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractPerform contractPerform=setData(user,keyId,contractDealId,customerInfoId,signDate,contractMoney);

        if (StringUtils.isNotEmpty(keyId)) {
            contractPerformService.approve(contractPerform, dutyService.get(curDutyId), comment);
        } else {
            contractPerformService.commit(contractPerform, "com.fz.us.oa.core.entity.com.ContractPerform", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        ContractPerform contractPerform=contractPerformService.get(keyId);
        contractPerformService.approve(contractPerform, dutyService.get(curDutyId), comment);

        rMap.put("message", "提交成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //退回
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            ContractPerform contractPerform=contractPerformService.get(keyId);
            contractPerformService.back(contractPerform, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","退回成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //否决
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            ContractPerform contractPerform=contractPerformService.get(keyId);
            contractPerformService.deny(contractPerform, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message","否决成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }


    /**
     * 履约登记
     */
    @RequestMapping(value = "toDetail", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String toDetail(@CurrentUser User user, Model model, String parentId) {
        model.addAttribute("parentId", parentId);
        return "/main/menu/com/contractPerformDetail";
    }

    /**
     * 履约登记
     */
    @RequestMapping(value = "detailList", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> detailList(@CurrentUser User user,Model model,
                                    String type, String parentId,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {


        Map<String, Object> params=new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("type", type);
        params.put("contractPerform", contractPerformService.get(parentId));
        List<PerformDetail> performDetailList=performDetailService.getList(params);

        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(PerformDetail detail: performDetailList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",detail.getId());
            rMap.put("date",DataUtil.DateToString(detail.getDate(),"yyyy-MM-dd"));
            rMap.put("money",detail.getMoney());
            dataRows.add(rMap);
        }

        data.put("dataRows", dataRows);
        return data;
    }

    /**
     * 履约登记表单页面
     */
    @RequestMapping(value = "addDetailPage", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String addDetailPage(@CurrentUser User user, Model model, String parentId, String type) {
        model.addAttribute("parentId", parentId);
        model.addAttribute("type", type);
        return "/com/addDetail_input";
    }

    /**
     * 详情保存操作
     */
    @RequestMapping(value = "saveDetail", method = RequestMethod.POST)
    public Object saveDetail(@CurrentUser User user, String contractPerformId, String type, String date, BigDecimal money) {

        Map<String,Object> rMap=new HashMap<String,Object>();
        PerformDetail performDetail=new PerformDetail();
        performDetail.setCompany(user.getCompany());
        performDetail.setCreater(user);
        performDetail.setProcessState(FlowEnum.ProcessState.Finished);
        performDetail.setState(BaseEnumManager.StateEnum.Enable);
        performDetail.setContractPerform(contractPerformService.get(contractPerformId));
        performDetail.setType(type);
        performDetail.setDate(DataUtil.StringToDate(date));
        performDetail.setMoney(money);
        String id=performDetailService.save(performDetail);
        rMap.put("message","保存成功");
        rMap.put("state", "1");
        rMap.put("keyId", id);
        return ajaxJson(rMap);
    }

}
